package cn.gzsf;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;

public class TestUserCRUD {
    //自行完成对user表的查询所有用户信息，根据id查询用户信息，新增，修改，删除
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        //1.提示用户登录
        System.out.println("请登录");
        //2.提示用户输入用户名
        System.out.println("请输入用户名");
        String username = scan.nextLine();
        //3。提示用户输入密码
        System.out.println("请输入密码");
        String password = scan.nextLine();
        System.out.println(username+":"+password);
        //4。调用方法根据用户名和密码登录
        //login(username,password);
        loginByPS(username,password);
        
    }
    //用PreparedStatement解决sql注入攻击
    private static void loginByPS(String username, String password) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConn();
            String sql = "select * from user where username=? and password=?";
            //获取PreparedStatement对象，并把sql传给数据库，预编译,形成sql骨架
            ps = conn.prepareStatement(sql);
            //设置参数
            ps.setString(1,username);
            ps.setString(2,password);
            //执行sql语句返回执行结果
            rs = ps.executeQuery();
            if(rs.next()){
                System.out.println("恭喜登录成功");
            }else {
                System.out.println("登录失败，用户名或者密码错误!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
          JDBCUtil.close(conn,ps,rs);
        }

    }

    //根据用户名和密码查询用户信息
    private static void login(String username, String password) {
        Connection conn = null;
        Statement stat = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConn();
            stat = conn.createStatement();
            String sql = "select * from user where username='"+username+"' and password='"+password+"'";
            rs = stat.executeQuery(sql);
            if(rs.next()){
                System.out.println("恭喜登录成功");
            }else {
                System.out.println("登录失败，用户名或者密码错误!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(conn,stat,rs);
        }
    }



}
